from alipay import AliPay, AliPayConfig
from django.http import HttpResponseBadRequest, JsonResponse

# Create your views here.
from django.views import View

from apps.order.models import OrderInfo
from apps.payment.models import Payment
from django_dome_meiduo import settings
from utils.viewmixin import LoginMixin


class PaymentView(LoginMixin, View):
    """订单支付功能"""

    def get(self, request, order_id):

        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return HttpResponseBadRequest('订单信息错误')

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=False,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        # 生成登录支付宝连接
        order_string = alipay.client_api(
            "alipay.trade.page.pay",
            biz_content={
                "subject": "美多商城%s" % order_id,
                "out_trade_no": order_id,
                "total_amount": str(order.total_amount),
                "product_code": "FAST_INSTANT_TRADE_PAY"
            },
            return_url=settings.ALIPAY_RETURN_URL
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'alipay_url': alipay_url})

    def put(self, request):
        # 获取参数

        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        signature = data.pop('sign')

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        # 创建AliPay对象

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
            verbose=False,
            config=AliPayConfig(timeout=30)
        )

        success = alipay.verify(data, signature)

        if success:
            order_id = data.get("out_trade_no")

            trade_id = data.get('trade_no')

            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

            # 响应
            return JsonResponse({'code': 0, 'errmsg': 'OK', 'trade_id': trade_id})

        else:
            return JsonResponse({"code": 400, "errmsg": "非法请求"})
